package com.leyou.goods.config;

import com.leyou.common.bean.Result;
import com.leyou.goods.service.GoodsService;
import com.leyou.goods.util.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author zqq
 * @ClassName GoodsHtmlGenerator
 * @Description: 生成商品详情静态页面
 * @date 2020/3/17-17:02
 */
@Component
@Slf4j
public class GoodsHtmlGenerator {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 创建html页面
     *
     * @param spuId
     * @throws Exception
     */
    public void createHtml(Long spuId) {
        PrintWriter writer = null;
        try {
            // 获取页面数据
            Result<Map<String, Object>> spuMap = this.goodsService.loadData(spuId);
            if(!spuMap.success())
                return;

            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariable("result",spuMap);

            // 创建输出流
            File file = new File("D:\\home\\html\\item\\" + spuId + ".html");
            if (!file.getParentFile().exists()) {  //检查目录是否存在，不存在创建
                file.getParentFile().mkdirs();
            }
            writer = new PrintWriter(file);
            // 执行页面静态化方法
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("页面静态化出错：{}，"+ e, spuId);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public void deleteHtml(Long id) {
        File file = new File("D:\\home\\html\\item\\", id.toString() + ".html");
        if (file.getParentFile().exists()) {
            file.delete();
        }
    }

    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(() -> createHtml(spuId));
    }
}
